package com.atguigu.sms.service.impl;

import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.sms.config.SmsConfig;
import com.atguigu.sms.constant.SmsSendRejectStrategyEnum;
import com.atguigu.sms.factory.SmsSendRejectStrategyFactory;
import com.atguigu.sms.handler.DefaultSmsTemplatePlaceHolderHandler;
import com.atguigu.sms.handler.SmsTemplatePlaceHolderHandler;
import com.atguigu.sms.model.param.SmsSendParam;
import com.atguigu.sms.service.SmsService;
import com.atguigu.sms.strategy.SmsTemplateContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private SmsConfig smsConfig;

    private SmsTemplatePlaceHolderHandler placeHolderHandler;


    @PostConstruct
    public void init() {
        SmsSendRejectStrategyEnum strategyEnum = smsConfig.getDefaultRejectStrategyEnum();
        if (null == strategyEnum) {
            strategyEnum = SmsSendRejectStrategyEnum.TOTALLY_MATCH;
        }
        placeHolderHandler = new DefaultSmsTemplatePlaceHolderHandler(SmsSendRejectStrategyFactory.getStrategy(strategyEnum));
    }


    /**
     * 发送短信方法
     *
     * @param param
     */
    @Override
    public void send(SmsSendParam param) {
        String templateContent = smsConfig.getTemplates().get(param.getTemplateCode());
        if (templateContent == null) {
            throw new GuliException(20001, "不正确的短信模板");
        }
        SmsTemplateContext templateContext = SmsTemplateContext.from(templateContent, param.getTemplateCode());
        String sendContent = placeHolderHandler.handler(templateContext, param.getParameter());
        log.info("短信发送: {}", sendContent);
    }
}
